package com.google.code.bankagregator.ui;

import com.google.code.bankagregator.core.DataManager;
import com.google.code.bankagregator.entities.Credit;
import com.google.code.bankagregator.entities.CreditType;
import com.google.code.bankagregator.entities.Currency;
import com.google.code.bankagregator.vo.CreditOffer;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "credit", urlPatterns = {"/credit"})
public class CredServlet extends HttpServlet {

    /**
     * Enterprise JavaBean
     * <p/>
     * Please use *dataManager* only (for get and put operations with Core).
     */
    @EJB
    DataManager dataManager;

    public int getInt(String param) {
        int res = 0;
        if ((!param.equals("")) && (!param.contains(" "))) {
            res = Integer.parseInt(param);
        }
        return res;
    }

    public double getDouble(String param) {
        double res = 0;
        if ((!param.equals("")) && (!param.contains(" "))) {
            res = Double.parseDouble(param.replace(",", "."));
        }
        return res;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("all") != null) {
            List<Credit> creditList = dataManager.getAllActiveCredits();
            request.setAttribute("res", creditList);
            request.getRequestDispatcher("allCredit.jspx").forward(request, response);
        } else {
            Credit criteria = new Credit();
            List<CreditOffer> creditOfferList = new ArrayList<>();

            String termStr = request.getParameter("term");
            String currencyStr = request.getParameter("currency");
            String maxAmStr = request.getParameter("maxAm");
            String prepaymentStr = request.getParameter("prepayment");
            String typeStr = request.getParameter("type");

            int term = getInt(termStr);
            int maxAm = getInt(maxAmStr);
            double prepayment = getDouble(prepaymentStr);

            criteria.setTerm(term);
            criteria.setMaxAmount(maxAm);
            criteria.setMinAmount(maxAm);
            criteria.setPrepayment(prepayment);
            criteria.setCurrency(Currency.valueOf(currencyStr));
            criteria.setType(CreditType.valueOf(typeStr));

            creditOfferList = dataManager.getSuitableCreditOffers(criteria);

            request.setAttribute("searchedCreditOffers", creditOfferList);
            request.getRequestDispatcher("credit.jspx").forward(request, response);
        }
    }
}